<?php 
/**
 * Copyright (c) 2010, Slawomir Mazur <mazursllawek@gmail.com>
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions 
 * are met:
 * 
 * o Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * o Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * o Neither the name of the Softisland nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Enter description here...
 *
 * @package     Admin
 * @subpackage  Admin_Auth
 * @copyright   Slawomir Mazur (c) 2010 (http://www.zend.com/zce.php?c=ZEND011643)
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @author      Slawomir Mazur <mazursllawek@gmail.com>
 */
?>
<div>
	<?php echo $this->messenger() ?>
	
	<?php if (!$this->company) : ?>
		<div class="messages"><div class="notice-msg"><ul><li><?php echo $this->translate('No company associated with this library! You can do this now by clicking <a href="%s">here</a>', $this->baseUrl('admin/library/edit/id/' . $this->libraryId)) ?></li></ul></div></div>
	<?php endif ?>
</div>
<h1>Convert library to database</h1>
<?php /* @var $_helper Gp_View_Helper_Reader */ ?>
<?php $_helper = $this->reader() ?>

<form id="rnaiRead" enctype="multipart/form-data" action="<?php echo $this->baseUrl('admin/library/read-post') ?>" method="post">
	<ul class="form-list">
		<li class="row clear">
			<label for="library-name" class="col1 required">Library name</label>
			<span class="col2"><?php echo $this->library()->getLibraryNameById($this->libraryId) ?></span>
		</li>
		<li class="row clear">
			<label for="library-decimal-separator" class="col1 required">Decimal separator<em>*</em></label>
			<span class="col2">
				<input type="text" name="library[decimal-separator]" id="library-decimal-separator" value="." class="input-text short-text required">
			</span>
		</li>
		<li class="row clear">
			<label for="library-value-delimiter" class="col1 required">Value Delimiter<em>*</em></label>
			<span class="col2">
				<input type="text" name="library[value-delimiter]" id="library-value-delimiter" value=";" class="input-text short-text required">&nbsp;(\t for tab)
			</span>
		</li>
		<li class="row clear">
			<label for="library-value-encloser" class="col1 required">Enclose Values In<em>*</em></label>
			<span class="col2">
				<input type="text" name="library[value-encloser]" id="library-value-encloser" value="&quot;" class="input-text short-text required">&nbsp;Warning! Empty value can cause problems with CSV format.
			</span>
		</li>
		<li class="row clear">
			<label for="library-rows" class="col1 required">Read rows<em>*</em></label>
			<span class="col2">
				<select name="library[rows]" id="library-rows" class="required">
					<?php echo $_helper->getRowsOptionsAsHtml() ?>
				</select>
			</span>
		</li>
		<li class="hidden-row row clear">
			<label for="library-rows-opts" class="col1 optional">Row ids</label>
			<span class="col2">
				<input type="text" name="library[rows-opts]" id="library-rows-opts" value="" class="input-text">
			</span>
		</li>
		<!-- 
		<li class="row clear">
			<label for="library-genecol" class="col1 required"><?php echo $this->translate('GeneID column') ?><em>*</em></label>
			<span class="col2">
				<span id="geneid-label"><?php echo $this->translate('Load document headers first') ?></span>
			</span>
		</li>
		 -->
		<li class="row clear">
			<label for="library-cols" class="col1 required"><?php echo $this->translate('Original column names in first row') ?><em>*</em></label>
			<span class="col2">
				<select name="library[cols]" id="library-cols" class="required">
					<option value="1" label="yes">Yes</option>
					<option value="2" label="no" selected="selected">No</option>
				</select>
			</span>
		</li>
		<li class="row clear">
			<span id="fieldMap"></span>
			<span class="col2">
				<button onclick="addMappingField();" type="button" class="button action"><span><span>Add mapping field</span></span></button>
				
				<button type="button" id="library-loader" onclick="loadDocumentColumnNames(this);" class="button"><span><span>Load document headers</span></span></button>
				<span id="ajaxLoader" class="clear">Data loading please wait...</span>
				
				<input type="button" class="no-display" id="library-placer" onclick="placeDocumentHeaders(this);" value="Place document headers">
			</span>
		</li>
		<li class="no-display">
			<input type="hidden" id="libraryId" name="library[id]" value="<?php echo $this->libraryId ?>">
		</li>
		<li class="row clear">
			<span class="col2">
				<button<?php if (!$this->company) : ?> disabled="disabled" <?php endif ?> class="button" id="submit"><span><span>Submit</span></span></button>
			</span>
		</li>
	</ul>
</form>
<div id="__mappingRowTemplate" class="no-display">
	<span style="display: block; padding: 0 0 5px 0;"> 
		In Database:
		<select name="library[map][db][]">
			<?php echo $_helper->getDatabaseAttributeNames() ?>
		</select>&lt;--&gt; 
		In File: <input name="library[map][file][]" class="input-text">
		<button style="" onclick="removeFieldMapping(this)" class="delete button" type="button"><span><span>Remove</span></span></button>
	</span>
</div>

<script type="text/javascript">
//<![CDATA[
	var columns = '';
    var columnsLoaded = false;
    
    $('#rnaiRead select').change(function() {
		var index = parseInt($(this).val());
		var parent = $(this).parent().parent();
		
		if (1 == index) {
			parent.next().addClass('hidden-row');
		} else {
			parent.next().removeClass('hidden-row');
		}
	});

	$('#submit').click(function() {
		$('#rnaiRead').validate();
	});

	function placeDocumentHeaders(button)
	{
		if (('' != columns) && columnsLoaded) {
			$('input[name="library[map][file][]"]').replaceWith(columns);
			$('#library-placer').attr('disabled', 'disabled');
		} else {
			alert('Headers are empty or not loaded');
		}
	}
	
	function loadDocumentColumnNames(loadButton)
	{
		var id = parseInt($('#libraryId').attr('value'));

		// no reason to reload
		if (('' != columns) && columnsLoaded) {
			return;
		}
		
		$.ajax({
			type: 'post',
			url: '<?php echo $this->baseUrl('admin/library/load-document-column-names') ?>',
			data: $('#rnaiRead').serialize(),
			dataType: 'json',
			beforeSend: function() {
				$('#ajaxLoader').show();
				$(loadButton).attr('disabled', 'disabled');
			},
			success: function (response) {
				if ('error' == response.status) {
					alert(response.message);
					$(loadButton).removeAttr('disabled');
					return;
				}
				
				html = '';
				for (id in response.columns) {
					html += '<option value="' + id + '">' + response.columns[id] + '</option>';
				}
				
				if ('' != html) {
					// replace geneid label at first place
					//$('#geneid-label').replaceWith('<select id="library-genecol" name="library[geneid]">' + html + '</select>');

					// replace mapping fields
					columns = '<select name="library[map][file][]">' + html + '</select>';
					//if (confirm('Replace fields with result data?')) {
						$('input[name="library[map][file][]"]').replaceWith(columns);
					//} else {
						//$('#library-placer').removeClass('no-display');
					//}
					$(loadButton).attr('disabled', 'disabled');
				} else {
					$(loadButton).removeAttr('disabled');
				}

				columnsLoaded = true;

				// setup mapping
				setupMapping();
			},
			error: function() {
				$(loadButton).removeAttr('disabled');
			},
			complete: function() {
				$('#ajaxLoader').hide();
			}
		});

		return false;
	}

	function addMappingField()
	{
		$('#fieldMap').append($('#__mappingRowTemplate').html());
		return false;
	}

	function removeFieldMapping(object)
	{
		$(object).parent().remove();
	}

	function setupMapping()
	{
		var fileColumnValues = $('select[name="library[map][file][]"] option');

		// create fields
		for (k = 0; k < fileColumnValues.length; k++) {
			addMappingField();
		}

		var databaseRows = $('#fieldMap select[name="library[map][db][]"]');
		var fileRows = $('#fieldMap select[name="library[map][file][]"]');

		var databaseColumns = null;
		var fileColumns = null;
		
		if (columnsLoaded) {
			for (j = 0; j < fileColumnValues.length; j++) {
				databaseColumns = databaseRows[j];
				fileColumns = fileRows[j];
				
				var selectedValue = fileColumns.options[j].text;
				var min = selectedValue.length; //selected value length
				var levenshteinDistance = min;
				var index = 0;
				
				for (i = 0; i < databaseColumns.length; i++) {
					levenshteinDistance = levenshtein(selectedValue, databaseColumns.options[i].text);
					if (min > levenshteinDistance) {
						min = levenshteinDistance; index = i;
					}
				}
				//change selected values
				fileColumns.options[j].selected = true;
				databaseColumns.options[index].selected = true;
			}
		}
		return false;
	}
//]]>
</script>